#!/bin/bash

CURR_DIR=$PWD

PCRE_VERSION="8.42"
ZLIB_VERSION="1.2.11"
NGINX_VERSION="1.15.0"

sudo addgroup --system nginx && \
    sudo adduser --debug --system --home /var/lib/nginx --shell /sbin/nologin --group nginx && \
    sudo mkdir -p /var/lib/nginx && \
    # dependence
    wget https://ftp.pcre.org/pub/pcre/pcre-$PCRE_VERSION.tar.gz && \
    tar zxf pcre-$PCRE_VERSION.tar.gz && \
    wget http://www.zlib.net/zlib-$ZLIB_VERSION.tar.gz && \
    tar xzf zlib-$ZLIB_VERSION.tar.gz && \
    git clone https://github.com/happyfish100/fastdfs-nginx-module.git --depth 1 && \
    sudo cp fastfds-nginx-module/src/mod_fastdfs.conf /etc/fdfs/
    wget http://nginx.org/download/nginx-$NGINX_VERSION.tar.gz && \
    tar zxf nginx-$NGINX_VERSION.tar.gz && \
    cd nginx-$NGINX_VERSION && \
    # start make
    ./configure --prefix=/usr/share/nginx \
        --sbin-path=/usr/sbin/nginx \
        --modules-path=/usr/lib/nginx/modules \
        --conf-path=/etc/nginx/nginx.conf \
        --error-log-path=/var/log/nginx/error.log \
        --http-log-path=/var/log/nginx/access.log \
        --pid-path=/run/nginx.pid \
        --lock-path=/var/lock/nginx.lock \
        --user=nginx \
        --group=nginx \
        --build=Fastdfs-Nginx \
        --http-client-body-temp-path=/var/lib/nginx/body \
        --http-proxy-temp-path=/var/lib/nginx/proxy \
        --http-scgi-temp-path=/var/lib/nginx/scgi \
        --http-uwsgi-temp-path=/var/lib/nginx/uwsgi \
        --with-pcre=../pcre-$PCRE_VERSION \
        --with-pcre-jit \
        --with-zlib=../zlib-$ZLIB_VERSION \
        --add-module=../fastdfs-nginx-module/src/ \
        --with-compat \
        --with-file-aio \
        --with-threads \
        --with-http_addition_module \
        --with-http_auth_request_module \
        --with-http_dav_module \
        --with-http_flv_module \
        --with-http_mp4_module \
        --with-http_random_index_module \
        --with-http_realip_module \
        --with-http_slice_module \
        --with-http_sub_module \
        --with-http_stub_status_module \
        --with-http_v2_module \
        --with-http_secure_link_module \
        --with-stream \
        --with-stream_realip_module \
        --with-debug \
        --with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2' \
        --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' && \
    make && \
    sudo make install && \
    cd .. && \
    sudo cp nginx.service /etc/systemd/system/nginx.service && \
    sudo systemctl start nginx.service && \
    sudo systemctl enable nginx.service
